# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web
import os
import json
import datetime

from openpyxl import Workbook
import openpyxl
from tornado.web import Application, RequestHandler


class baseHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT')
        self.set_header("Access-Control-Allow-Headers", "x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp")
        self.set_header("Access-Control-Allow-Credentials", "true")

    def options(self):
        pass



class MainHandler(baseHandler):
    def get(self):
        self.write("Hello world")
        print("开始启动")
        try:
            # os.system("D:\software\数采软件\A工位\Debug20220603V1\Debug\iSmartPLCDataCollect.exe")
            # os.system("ipconfig")
            # os.system("cd D:\software\数采软件\A工位\Debug20220603V1\Debug")
            # os.system("dir")
            # os.system(r"D:\software\Debug20220603V1\Debug\iSmartPLCDataCollect_start.bat")
            print("开始启动")

        except Exception as e:
            print("e=", e)

        print("启动成功")

    def post(self):
        print("self.request=", self.request)
        origin_url = self.request.headers.get('Origin')

        self.set_header("Access-Control-Allow-Origin", origin_url)
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        data = json.loads(self.request.body)
        print("data=", data)
        print("type(data)=", type(data))

        wsn = data["wsn"]
        psn = data["psn"]
        time = data["time"]
        ti = data["ti"]
        Rob_No = data["Rob_No"]
        FORCE = data["FORCE"]
        Not = data["Not"]
        pos = data["pos"]
        username = data["username"]

        print("wsn=", wsn)
        print("psn=", psn)
        print("time=", time)
        print("ti=", ti)
        print("Rob_No=", Rob_No)
        print("FORCE=", FORCE)
        print("Not=", Not)

        LocalTime = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        try:
            # filename = datetime.datetime.now().strftime("%Y-%m-%d.xlsx")
            filename = datetime.datetime.now().strftime("%Y-%m.xlsx")
            local_path = "D:\\PycharmProjects\\vietnam_tornado_export_excel" +"\\"
            local_path_and_filename = local_path + filename
            print("local_path_and_filename=", local_path_and_filename)
            if not os.path.isdir(local_path):
                # 本地目录%s不存在，创建本地目录
                os.makedirs(local_path)
            new_file = False
            if not os.path.isfile(str(local_path_and_filename)):
                new_file = True
                wb = Workbook()
                ws = wb.active
                ws.append(['username','psn', 'wsn', 'time','Rob_No', 'pos', 'FORCE','STROKE','Angle','DEPTH','TORQUE','Not'])
                wb.save(filename)
            print("new_file=", new_file)

            if wsn != "OP167-1" and wsn != "OP167-2":
                STROKE = data["STROKE"]
                print("STROKE=", STROKE)
                workbook = openpyxl.load_workbook(filename)

                # 激活工作表
                sheet = workbook.active

                # 要追加的内容
                # new_row = [username, psn, wsn, time, Rob_No, pos, FORCE, STROKE, "-","-","-",Not]
                new_row = [username, psn, wsn, str(LocalTime), Rob_No, pos, FORCE, STROKE, "-","-","-",Not]

                # 追加内容到工作表的下一行
                sheet.append(new_row)

                # 保存工作簿
                workbook.save(filename)

            else:
                Angle = data["Angle"]
                DEPTH = data["DEPTH"]
                TORQUE = data["TORQUE"]
                print("Angle=", Angle)
                print("DEPTH=", DEPTH)
                print("TORQUE=", TORQUE)

                # STROKE = data["STROKE"]
                # print("STROKE=", STROKE)
                workbook = openpyxl.load_workbook(filename)

                # 激活工作表
                sheet = workbook.active

                # 要追加的内容
                new_row = [username, psn, wsn, str(LocalTime), Rob_No, pos, FORCE, "-", Angle, DEPTH, TORQUE, Not]

                # 追加内容到工作表的下一行
                sheet.append(new_row)

                # 保存工作簿
                workbook.save(filename)
        except Exception as e:
            filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.xlsx")
            local_path = "D:\\PycharmProjects\\vietnam_tornado_export_excel" + "\\"
            local_path_and_filename = local_path + filename
            print("local_path_and_filename=", local_path_and_filename)
            if not os.path.isdir(local_path):
                # 本地目录%s不存在，创建本地目录
                os.makedirs(local_path)
            new_file = False
            if not os.path.isfile(str(local_path_and_filename)):
                new_file = True
                wb = Workbook()
                ws = wb.active
                ws.append(
                    ['username', 'psn', 'wsn', 'time', 'Rob_No', 'pos', 'FORCE', 'STROKE', 'Angle', 'DEPTH', 'TORQUE',
                     'Not'])
                wb.save(filename)
            print("new_file=", new_file)

            if wsn != "OP167-1" and wsn != "OP167-2":
                STROKE = data["STROKE"]
                print("STROKE=", STROKE)
                workbook = openpyxl.load_workbook(filename)

                # 激活工作表
                sheet = workbook.active

                # 要追加的内容
                new_row = [username, psn, wsn, str(LocalTime), Rob_No, pos, FORCE, STROKE, "-", "-", "-", Not]

                # 追加内容到工作表的下一行
                sheet.append(new_row)

                # 保存工作簿
                workbook.save(filename)

            else:
                Angle = data["Angle"]
                DEPTH = data["DEPTH"]
                TORQUE = data["TORQUE"]
                print("Angle=", Angle)
                print("DEPTH=", DEPTH)
                print("TORQUE=", TORQUE)

                # STROKE = data["STROKE"]
                # print("STROKE=", STROKE)
                workbook = openpyxl.load_workbook(filename)

                # 激活工作表
                sheet = workbook.active

                # 要追加的内容
                new_row = [username, psn, wsn, str(LocalTime), Rob_No, pos, FORCE, "-", Angle, DEPTH, TORQUE, Not]

                # 追加内容到工作表的下一行
                sheet.append(new_row)

                # 保存工作簿
                workbook.save(filename)



class CORSListHandler(RequestHandler):
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')  # 允许所有域名
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Allow-Headers', '*')


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', MainHandler),
            (r'/crossdomain', CORSListHandler),
        ]
        tornado.web.Application.__init__(self, handlers)

if __name__=="__main__":
    app = Application()
    app.listen(9000)
    print("Tornado Started in port 9000，http://127.0.0.1:9000")
    tornado.ioloop.IOLoop.current().start()